package edu.msu.cse.meldru20.project1;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.TextView;
import edu.msu.cse.meldru20.project1.EditingView.Drawing;

public class GameManager {
	
	private String player1 = "";
	
	private String player2 = "";
	
	public enum Players {PLAYER1, PLAYER2};
	
	public enum GameModes {DRAWING, GUESSING};
	
	private Drawing theDrawing = new Drawing();
	
	public void SetDrawing(Drawing d)
	{
		theDrawing = d;
	}
	
	public enum Categories {
		ANIMAL, 
		BUILDING, 
		OBJECT, 
		ACTION, 
		MSU;
		
		private static final List<Categories> VALUES =
	    	Collections.unmodifiableList(Arrays.asList(values()));
		private static final int SIZE = VALUES.size();
		private static final Random RANDOM = new Random();

		public static Categories randomCategory()  {
			return VALUES.get(RANDOM.nextInt(SIZE));
	    }
	}
	
	/*
	 * Keep track of the current player
	 */
	private Players currentPlayer;
	
	/*
	 * Keep track of the current game mode
	 */
	private GameModes currentGameMode;
	
	/*
	 * Keep track of the current category
	 */
	private Categories currentCategory = null;
	
	private String drawingName = "";
	
	private String drawingHint = "";
	
	private int numOfRounds = 1;
	
	private int currentRound = 0;
	
	/*
	 * A round will consist of each player taking a turn drawing and 
	 * guessing. This will be used as a flag to determine once the roles
	 * have swapped and we need to advance to the next round.
	 */
	private boolean firstSetDone = false;
	
	final static int MAX_ROUNDS = 10;
	
	private int player1Score = 0;
	
	private int player2Score = 0;
	
	private int Timer = 130000;
	
	
	/*
	 * Singleton pattern object
	 */
	private static final GameManager game = new GameManager();

	// Can't be created from any other class
	private GameManager() {
		
	}
	
	/*
	 * Set up a fresh instance of the GameManager
	 */
	public void Init() {
		player1 = "";
		player2 = "";
		
		currentPlayer = Players.PLAYER1;
		currentGameMode = GameModes.DRAWING;
		currentCategory = null;
		
		currentRound = 1; 
		firstSetDone = false;
		numOfRounds = 1;
		
		drawingName = "";
		drawingHint = "";
		
		player1Score = 0;
		player2Score = 0;
		
		Timer = 130000;
	}
	
	/*
	 * Provides references to the GameManager to any class that requests it
	 */
	public static GameManager get() {
		return game;
	}

	public String getPlayer1() {
		return player1;
	}

	public void setPlayer1(String player1) {
		this.player1 = player1;
	}

	public String getPlayer2() {
		return player2;
	}

	public void setPlayer2(String player2) {
		this.player2 = player2;
	}

	public String getDrawingName() {
		return drawingName;
	}

	public void setDrawingName(String drawingName) {
		this.drawingName = drawingName;
	}

	public String getDrawingHint() {
		return drawingHint;
	}

	public void setDrawingHint(String drawingHint) {
		this.drawingHint = drawingHint;
	}
	
	/*
	 * Advances through the game modes and determines which player's turn it is
	 */
	public void advanceGame(Context activity) {
		// Change players if we just finished the editing activity
		if(currentGameMode == GameModes.DRAWING) {
			// Java enums suck
			if(currentPlayer == Players.PLAYER1) {
				currentPlayer = Players.PLAYER2;
			}
			else {
				currentPlayer = Players.PLAYER1;
			}
			// Advance the game mode
			currentGameMode = GameModes.GUESSING;
			
			Intent intent = new Intent(activity, GuessActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			intent.putExtra(EditingActivity.TRANSFER, theDrawing);
			activity.startActivity(intent);
		}
		// Just finished guessing
		else {
			// Advance the game mode
			currentGameMode = GameModes.DRAWING;
			
			drawingName = "";
			drawingHint = "";
			
			// Start the next round if we aren't on the last round and final set
			if(currentRound < numOfRounds || !firstSetDone) {
				if(!firstSetDone) {
					firstSetDone = true;
				}
				else {
					currentRound++;
					firstSetDone = false;
				}
				
				Intent intent = new Intent(activity, EditingActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
				activity.startActivity(intent);
			}
			// We finished the final round, display the winner and return to the main menu
			else {
				// Head off to the winner page
				Intent intent = new Intent(activity, FinalScoreActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
				activity.startActivity(intent);
			}
		}
	}

	public int getNumOfRounds() {
		return numOfRounds;
	}

	public void setNumOfRounds(int numOfRounds) {
		this.numOfRounds = numOfRounds;
	}
	
	public void handleBackButton(final Context activity) {
		
		final AlertDialog.Builder alert_builder = new AlertDialog.Builder(activity);
		alert_builder.setTitle("Quit??");
		alert_builder.setMessage("Would you like to quit the current game " +
				"and return to the main menu?");
		
	    alert_builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	        	// Reset the game
				Init();
				
				// Return to the main menu
				Intent intent = new Intent(activity, MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
				activity.startActivity(intent);
	        }
	    });

	    alert_builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int whichButton) {
	            dialog.cancel();
	        }
	    });
	    
	    alert_builder.show();
	}
	
	/*
	 * Called at the beginning of an activity to indicate which player's turn it
	 * is and any other necessary instructions.
	 */
	public void showInstructions(Context activity) {
		
		String player = getCurrentPlayer();
		
		switch (currentGameMode) {
		
			case DRAWING:
				// Randomly choose a category for the player to draw
				currentCategory = Categories.randomCategory();
				
				AlertDialog dialogD = new AlertDialog.Builder(activity)
				.setTitle(player + "'s turn to draw!!")  
				.setMessage("Please pass the game to Player: " + player + ". " + player + ", it is your turn to draw " +
						"and your category is:\n\n" + getCurrentCategory() + "\n\nPress Ready! when you want to get started." )
				.setPositiveButton("Ready!", null)  
				.show(); 
				
				TextView messageD = (TextView)dialogD.findViewById(android.R.id.message);
				messageD.setGravity(Gravity.CENTER);
				
				WindowManager.LayoutParams lpD = dialogD.getWindow().getAttributes();
				lpD.dimAmount = 0.98f;
				dialogD.getWindow().setAttributes(lpD);
				dialogD.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
				
				break;
			case GUESSING:
				AlertDialog dialogG = new AlertDialog.Builder(activity)
				.setTitle(player + "'s turn to guess!!")  
				.setMessage("Please pass the game to Player: " + player + ". " + player + ", it is your turn to guess " +
						"and the category is:\n\n" + getCurrentCategory() + "\n\nPress Ready! when you want to get started." +
								"\n\n**WARNING: The timer will start right away**" )
				.setPositiveButton("Ready!", new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int whichButton) {
			        	// TODO
			        	// Add code to start up the timer here,
			        	// you should be able to call a function from the activity
			        	// I think -Mike
			        	// OR
			        	// You could create the timer in the game manager, still you 
			        	// would use this listener to star up the timer
			        }
				})
				.show(); 
				
				TextView messageG = (TextView)dialogG.findViewById(android.R.id.message);
				messageG.setGravity(Gravity.CENTER);
				
				WindowManager.LayoutParams lpG = dialogG.getWindow().getAttributes();
				lpG.dimAmount = 0.98f;
				dialogG.getWindow().setAttributes(lpG);
				dialogG.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
				break;
			default:
				break;
		}
	}
	
	public String getCurrentPlayer() {
		if(currentPlayer == Players.PLAYER1) {
			return player1;
		}
		return player2;
	}
	
	public String getCurrentCategory() {
		switch(currentCategory) {
		case ACTION:
			return "Action";
		case ANIMAL:
			return "Animal";
		case BUILDING:
			return "Building";
		case MSU:
			return "MSU";
		case OBJECT:
			return "Object";
		default:
			return "null";
		}
	}

	public int getCurrentRound() {
		return currentRound;
	}

	public int getPlayer1Score() {
		return player1Score;
	}

	public void setPlayer1Score(int player1Score) {
		this.player1Score = player1Score;
	}

	public int getPlayer2Score() {
		return player2Score;
	}

	public void setPlayer2Score(int player2Score) {
		this.player2Score = player2Score;
	}
	
	public int getTimer() {
		return Timer;
	}

	public void setTimer(int Timer) {
		this.Timer = Timer;
	}

}
